import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Card,
  Button,
  Input,
  Table,
  Form,
  Modal,
  Divider,
  Icon,
  Tooltip,
  Select,
  Row,
  Col,
  Alert,
  Popconfirm,
  Pagination,
  message,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;

const DeviceForm = Form.create()(props => {
  const { modalVisible, form, options, handleModalVisible, handleAdd, clearSelect } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      clearSelect();
      handleAdd(fieldsValue, form);
    });
  };
  // 组件树形控件 子节点渲染
  // const renderTreeNodes = data =>
  //   data.map(item => {
  //     if (item.children) {
  //       return (
  //         <TreeNode title={item.name} key={item.id} value={item.id}>
  //           {renderTreeNodes(item.children)}
  //         </TreeNode>
  //       );
  //     }
  //     return <TreeNode title={item.name} key={item.id} value={item.id}></TreeNode>;
  //   });
  return (
    <Modal
      title={
        <span>
          <FormattedMessage id="app.dm.devices.add" />
          <em className={styles.optional}>
            <Tooltip title={<FormattedMessage id="app.dm.devices.add.help" />}>
              <Icon type="info-circle-o" style={{ marginLeft: 4 }} />
            </Tooltip>
          </em>
        </span>
      }
      destroyOnClose
      visible={modalVisible}
      width={618}
      onCancel={() => handleModalVisible()}
      onOk={okHandle}
    >
      <Alert
        message={formatMessage({ id: 'app.dm.devices.deviceName.info' })}
        type="info"
        showIcon
      />
      <Form>
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.product' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('productId', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.devices.info.productId.place' }),
              },
            ],
          })(<Select>{options}</Select>)}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.name' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('name', {
            rules: [
              { required: false, message: formatMessage({ id: 'app.dm.devices.info.name.place' }) },
            ],
          })(
            <div>
              <Input
                placeholder={formatMessage({ id: 'app.dm.devices.info.name.place' })}
                style={{ width: 540 }}
              />
              <Tooltip title={<FormattedMessage id="app.dm.devices.info.name.help" />}>
                <Icon type="info-circle-o" style={{ marginLeft: 10 }} />
              </Tooltip>
            </div>,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.label' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('label', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.devices.info.label.place' }),
              },
            ],
          })(
            <div>
              <Input
                placeholder={formatMessage({ id: 'app.dm.devices.info.label.place' })}
                style={{ width: 540 }}
              />
              <Tooltip title={<FormattedMessage id="app.dm.devices.info.label.help" />}>
                <Icon type="info-circle-o" style={{ marginLeft: 10 }} />
              </Tooltip>
            </div>,
          )}
        </FormItem>
        {/* <FormItem
          label={formatMessage({ id: 'app.dm.devices.group' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('groupIds', {
          })(
            <TreeSelect
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder={formatMessage({ id: 'app.dm.devices.info.group.place' })}
            allowClear
            multiple
          >
            {renderTreeNodes(groups)}
          </TreeSelect>,
          )}
        </FormItem> */}
        <FormItem
          label={formatMessage({ id: 'app.dm.devices.remarkName' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('remarkName', {
            rules: [
              { required: false, message: formatMessage({ id: 'app.dm.devices.info.name.place' }) },
            ],
          })(
            <div>
              <Input
                placeholder={formatMessage({ id: 'app.dm.devices.info.name.place' })}
                style={{ width: 540 }}
              />
              <Tooltip title={<FormattedMessage id="app.dm.devices.info.remarkName.help" />}>
                <Icon type="info-circle-o" style={{ marginLeft: 10 }} />
              </Tooltip>
            </div>,
          )}
        </FormItem>
      </Form>
    </Modal>
  );
});

@connect(({ devices, loading }) => ({
  devices,
  loading: loading.models.devices,
}))
@Form.create()
class Devices extends PureComponent {
  state = {
    modalVisible: false,
    selectedRowKeys: [],
  };

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.devices.name' }),
      dataIndex: 'name',
    },
    {
      key: 'productName',
      title: formatMessage({ id: 'app.dm.devices.product' }),
      dataIndex: 'productName',
    },
    {
      key: 'label',
      title: formatMessage({ id: 'app.dm.devices.label' }),
      dataIndex: 'label',
    },
    {
      key: 'type',
      title: formatMessage({ id: 'app.dm.devices.nodeType' }),
      render: (text, record) => {
        if (record.type === 1) {
          return <FormattedMessage id="app.dm.devices.info.type.device" />;
        }
        if (record.type === 2) {
          return <FormattedMessage id="app.dm.devices.info.type.gateway" />;
        }
        return null;
      },
    },
    {
      key: 'state',
      title: formatMessage({ id: 'app.dm.devices.state' }),
      render: (text, record) => {
        if (record.state === 1) {
          return <FormattedMessage id="app.dm.devices.info.notactive" />;
        }
        if (record.state === 2) {
          return <FormattedMessage id="app.dm.devices.info.enable" />;
        }
        if (record.state === 3) {
          return <FormattedMessage id="app.dm.devices.info.disabled" />;
        }
        if (record.state === 4) {
          return <FormattedMessage id="app.dm.devices.info.online" />;
        }
        if (record.state === 5) {
          return <FormattedMessage id="app.dm.devices.info.offline" />;
        }
        return null;
      },
    },
    {
      key: 'lastUpTime',
      title: formatMessage({ id: 'app.dm.devices.lastTime' }),
      dataIndex: 'lastUpTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.devices.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record)}>
            <FormattedMessage id="app.dm.devices.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>
                    {formatMessage({ id: 'app.dm.devices.del.confirm' }, { name: record.name })}
                  </span>
                </div>
                <div>
                  <span>{formatMessage({ id: 'app.dm.devices.del.prompt' })}</span>
                </div>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id, record.childDevNum)}
          >
            <a>
              <FormattedMessage id="app.dm.devices.table.action.del" />
            </a>
          </Popconfirm>
          <span>
            {record.type === 2 && record.protocol !== 2 ? (
              <span>
                <Divider type="vertical" />
                <a onClick={() => this.handleChildView(record)}>
                  <span>
                    {formatMessage(
                      { id: 'app.dm.devices.table.action.childDevice' },
                      { num: record.childDevNum },
                    )}
                  </span>
                </a>
              </span>
            ) : (
              undefined
            )}
          </span>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, location } = this.props;
    if (location.query.pid) {
      dispatch({
        type: 'devices/init',
        payload: { productId: location.query.pid },
      });
    } else {
      dispatch({
        type: 'devices/init',
      });
    }
    // dispatch({
    //   type: 'devices/fetchGroups',
    // });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleDelete = (id, childDevNum) => {
    if (childDevNum > 0) {
      message.error({ content: formatMessage({ id: 'app.dm.devices.del.prompt' }), key: 1 });
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'devices/del',
      payload: id,
    });
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'devices/add',
      payload: {
        ...fields,
      },
      form,
      handleModalVisible,
    });
  };

  handleView = record => {
    router.push({
      pathname: `/dm/devices/detail/${record.id}`,
      state: {
        showChildDeviceTab: record.type === 2 && record.protocol !== 2,
        activeChildDeviceTab: false,
        protocol: record.protocol,
        protocolId: record.protocolId,
      },
    });
  };

  handleChildView = record => {
    router.push({
      pathname: `/dm/devices/detail/${record.id}`,
      state: {
        showChildDeviceTab: true,
        activeChildDeviceTab: true,
        protocol: record.protocol,
        protocolId: record.protocolId,
      },
    });
  };

  render() {
    const {
      devices: { list, pagination, current, products, deviceCount, activateCount, groupList },
      loading,
      dispatch,
      location,
    } = this.props;

    const { modalVisible, selectedRowKeys } = this.state;

    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;

    const clearSelect = () => {
      this.setState({
        selectedRowKeys: [],
      });
    };

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        clearSelect();
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        clearSelect();
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: pagination.currentSize } },
        });
      },
    };

    const changeProduct = value => {
      clearSelect();
      dispatch({
        type: 'devices/fetchAndCount',
        payload: { ...getFieldsValue(), ...{ productId: value } },
      });
    };

    const refresh = () => {
      clearSelect();
      dispatch({
        type: 'devices/refresh',
        payload: { ...getFieldsValue(), ...{ name: '' } },
      });
    };

    const search = value => {
      clearSelect();
      dispatch({
        type: 'devices/fetch',
        payload: { ...getFieldsValue(), ...{ name: value } },
      });
    };

    const batchEnable = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'enable', keys: selectedRowKeys },
      });
    };

    const batchDisable = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'disable', keys: selectedRowKeys },
      });
    };

    const batchDelete = () => {
      clearSelect();
      dispatch({
        type: 'devices/batch',
        payload: { type: 'delete', keys: selectedRowKeys },
      });
    };

    const Info = ({ title, value, bordered, help }) => (
      <div className={styles.headerInfo}>
        <span>
          {title}
          <Tooltip title={help}>
            <Icon type="info-circle-o" style={{ marginLeft: 4 }} />
          </Tooltip>
        </span>
        <p>{value}</p>
        {bordered && <em />}
      </div>
    );

    let options = [];

    if (products) {
      options = products.map(d => <Option key={d.id}>{d.name}</Option>);
    }

    const parentMethods = {
      options,
      current,
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
      groups: groupList,
    };

    const hasSelected = selectedRowKeys.length;

    const isSelected = selectedRowKeys.length === 0;

    const rowSelection = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.setState({
          selectedRowKeys: selectedKeys,
        });
      },
    };

    return (
      <PageHeaderWrapper title={formatMessage({ id: 'app.dm.devices.title' })}>
        <div className={styles.standardList}>
          <Form layout="inline">
            <Card bordered={false} style={{ marginBottom: '24px' }}>
              <Row>
                <Col
                  sm={5}
                  xs={24}
                  className={styles.headerInfo}
                  style={{ paddingTop: '12px', paddingRight: '10px' }}
                >
                  <FormItem>
                    {getFieldDecorator('productId', {
                      initialValue: location.query.pid ? location.query.pid : -1,
                    })(
                      <Select style={{ width: '200px' }} showSearch onChange={changeProduct}>
                        <Option key={-1} value={-1}>
                          <FormattedMessage id="app.dm.devices.product.all" />
                        </Option>
                        {options}
                      </Select>,
                    )}
                  </FormItem>
                  <em />
                </Col>
                <Col sm={5} xs={24}>
                  <Info
                    title={formatMessage({ id: 'app.dm.devices.sum' })}
                    help={formatMessage({ id: 'app.dm.devices.sum.help' })}
                    value={deviceCount}
                    bordered
                  />
                </Col>
                <Col sm={5} xs={24}>
                  <Info
                    title={formatMessage({ id: 'app.dm.devices.active' })}
                    help={formatMessage({ id: 'app.dm.devices.active.help' })}
                    value={activateCount}
                    bordered
                  />
                </Col>
                <Col sm={5} xs={24}>
                  <Info
                    title={formatMessage({ id: 'app.dm.devices.online' })}
                    help={formatMessage({ id: 'app.dm.devices.online.help' })}
                    value="10"
                    bordered
                  />
                </Col>
                <Col
                  sm={4}
                  xs={24}
                  className={styles.headerInfo}
                  style={{ paddingTop: '12px', paddingRight: '10px' }}
                >
                  <Button onClick={refresh}>
                    <FormattedMessage id="app.dm.devices.refresh" />
                  </Button>
                </Col>
              </Row>
            </Card>
            <Card bordered={false}>
              <div className={styles.extraContent}>
                <Row>
                  <Col span={12}>
                    {/* <span style={{fontSize:'16px',color:'rgba(0, 0, 0, 0.85)',fontWeight:500}}><FormattedMessage id="app.dm.devices.title" /></span> */}
                    <FormItem>
                      {getFieldDecorator('name')(
                        <Search
                          className={styles.extraContentSearch}
                          placeholder={formatMessage({ id: 'app.dm.devices.search' })}
                          onSearch={search}
                        />,
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    <FormItem>
                      <Button style={{ marginLeft: 8 }}>
                        <FormattedMessage id="app.dm.devices.add.batch" />
                      </Button>
                    </FormItem>
                    <FormItem style={{ marginRight: 0 }}>
                      <Button
                        type="primary"
                        style={{ marginLeft: 8 }}
                        onClick={() => this.handleModalVisible(true)}
                      >
                        <FormattedMessage id="app.dm.devices.add" />
                      </Button>
                    </FormItem>
                  </Col>
                </Row>
                {/* <Row>
                  <FormItem>
                    {getFieldDecorator('name')(
                      <Search className={styles.extraContentSearch} placeholder={formatMessage({id:'app.dm.devices.search'})} onSearch={search} />
                    )}
                  </FormItem>
                </Row> */}
              </div>
              <div className={styles.tableAlert} style={{ marginTop: 15 }}>
                <Alert
                  message={
                    <Fragment>
                      <FormattedMessage id="app.dm.devices.table.selected" />{' '}
                      <a style={{ fontWeight: 600 }}>{hasSelected}</a>{' '}
                      <FormattedMessage id="app.dm.devices.table.selected.item" />
                      &nbsp;&nbsp;
                      <a onClick={clearSelect} style={{ marginLeft: 24 }}>
                        <FormattedMessage id="app.dm.devices.table.clear" />
                      </a>
                    </Fragment>
                  }
                  type="info"
                  showIcon
                />
              </div>
              <Table
                columns={this.columns}
                rowSelection={rowSelection}
                dataSource={list}
                pagination={false}
                loading={loading}
                rowKey="id"
              />
              <Row style={{ marginTop: 15 }}>
                <Col span={12} style={{ lineHeight: '40px', height: '40px' }}>
                  <FormItem>
                    <Button type="primary" disabled={isSelected} onClick={batchDelete}>
                      <FormattedMessage id="app.dm.devices.del.batch" />
                    </Button>
                  </FormItem>
                  <FormItem>
                    <Button
                      type="primary"
                      disabled={isSelected}
                      onClick={batchDisable}
                      style={{ marginLeft: 8 }}
                    >
                      <FormattedMessage id="app.dm.devices.disabled.batch" />
                    </Button>
                  </FormItem>
                  <FormItem>
                    <Button
                      type="primary"
                      disabled={isSelected}
                      onClick={batchEnable}
                      style={{ marginLeft: 8 }}
                    >
                      <FormattedMessage id="app.dm.devices.use.batch" />
                    </Button>
                  </FormItem>
                </Col>
                <Col
                  span={12}
                  style={{
                    textAlign: 'right',
                    lineHeight: '40px',
                    height: '40px',
                    paddingTop: '4px',
                  }}
                >
                  <Pagination {...paginationProps} />
                </Col>
              </Row>
            </Card>
          </Form>
        </div>
        <DeviceForm {...parentMethods} clearSelect={clearSelect} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default Devices;
